<?php

namespace app\model;

use think\helper\Str;
use think\Model;

class MerchantService extends Model
{
    public function merchant()
    {
        return $this->hasOne(Merchant::class,"id","mid");
    }
    public function serviceSave(): array
    {
        $param = request()->post();
        $param['content'] = htmlspecialchars($param['content'] ?? '');
        if (empty($param['id'])) {
            $param['code'] = $this->code();
        }
        $this->exists(!empty($param['id']))->save($param);
        return $this->toArray();
    }

    public function serviceLst(): array
    {
        $param = request()->param();
        $data = $this->with(['merchant'])->when(!empty($param['name']), function ($query) use ($param) {
            $query->where('name', 'like', "%{$param['name']}%");
        })->when(!empty($param['mid']), function ($query) use ($param) {
            $query->where('mid', $param['mid']);
        })->order('create_time', 'desc')->paginate(['list_rows' => 30, 'page' => $param['page'] ?? 1])->toArray();
        return pageData($data);
    }

    protected function code(): string
    {
        $code = Str::random(6, 9);
        $count = $this->where('code', $code)->count();
        if ($count > 0) {
            return $this->code();
        }
        return $code;
    }
}
